import * as PIXI from "pixi.js";
let realPath;
let shapeContainer;
let beginPos;
let pos = [];

function intermidPx(pxA, pxB, size = 16) {
  let arr = [];
  let x = (pxB.x - pxA.x) / (size + 1);
  let y = (pxB.y - pxA.y) / (size + 1);
  for (let i = 0; i <= size; i++) {
    arr.push({
      x: Math.round(pxA.x + i * x),
      y: Math.round(pxA.y + i * y),
    });
  }
  arr.push(pxB)
  return arr;
}

function drawPos(main) {
  if(!realPath) return;
  realPath.clear();
  pos = intermidPx(beginPos, main, Math.round(Math.sqrt(main.height**2, main.width**2))) || [];
  pos.forEach((p) => {
    realPath.beginFill(main.pointColor,1);
    realPath.drawRect(p.x, p.y, 1, 1);
    realPath.endFill();
  });
}

export default function (pxs, main) {
  if (main.eventName == "pointerDown") {
    shapeContainer = main.shapeContainer;
    realPath = new PIXI.Graphics();
    shapeContainer.addChild(realPath);
    beginPos = pxs[0];
  }
  if (main.eventName == "pointerMove" && !main.isUp) {
    drawPos(main);
  }
  if (main.eventName == "pointerUp" || main.eventName =="pointerOut") {
      if(!realPath) return;
      realPath.destroy(true, true);
      realPath = null;
      if (pos.length == 0) return;
      main.pxMap.forEach(px=>{
        if(pos.some(p=>p.x==px.x&&p.y==px.y)){
            px.color = main.pointColor;
            px.alpha = 1;
        }
      })
      pos.length = 0;
      main.update();   
  }
}
